package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.User;
import model.Wish;
import ejb.Facade;

/**
 * Servlet implementation class AjouterEnvieServlet
 */
@WebServlet("/AjouterEnvieServlet")
public class AjouterEnvieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjouterEnvieServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    /**
     * Constructeur avec parametre
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public AjouterEnvieServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request, response);
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//On regarde si on cree une envie
		String creation = request.getParameter("creation");
		if( creation != null && creation.equals("1") ){
			HttpSession session = request.getSession();
			//Recuperation de l'user courant et facade
			User user = (User) request.getSession().getAttribute("user");
			Facade fac = (Facade) request.getSession().getAttribute("Facade");
			//Recuparation des donnnees du formulaire
			String titre = request.getParameter("titre");
			String lien = request.getParameter("lien");
			String description = request.getParameter("description");
			//Creation envie
			Wish w = new Wish();
			w.setMessage(titre);
			w.setLink(lien);
			w.setDescription(description);
			w.setFrom(user);
			//Ajouter
			fac.addWish(user, w);
			//Redirection
			new IndexServlet(request, response);
		} else {
			request.getRequestDispatcher("jsp/ajouterEnvie.jsp").forward(request, response);
		}
	}
	
}
